package com.lzy.imagepickerdemo.wxdemo;


import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridAbility;
import com.lzy.imagepicker.ui.ImagePreviewAbility;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.imagepickerdemo.ResourceTable;
import com.lzy.imagepickerdemo.imageloader.UILImageLoader;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.components.TableLayoutManager;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.dialog.ListDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * ================================================
 * 作    者：ikkong （ikkong@163.com），修改 jeasonlzy（廖子尧）
 * 版    本：1.0
 * 创建日期：2016/5/19
 * 描    述：
 * 修订历史：微信图片选择的Adapter, 感谢 ikkong 的提交
 * ================================================
 */
public class WxDemoAbility extends Ability implements ImagePickerAdapter.OnRecyclerViewItemClickListener {

    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    private ImagePickerAdapter adapter;
    private ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 8;               //允许选择图片最大数

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_activity_wxdemo);

        //最好放到 Application oncreate执行
        initImagePicker();
        initWidget();
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new UILImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    private void initWidget() {
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_recyclerView);
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);
        TableLayoutManager layoutManager = new TableLayoutManager();
        layoutManager.setColumnCount(4);
        listContainer.setLayoutManager(layoutManager);
//        listContainer.setHasFixedSize(true);
        listContainer.setItemProvider(adapter);
    }

    private ListDialog showDialog(IDialog.ClickedListener listener, List<String> names) {
        ListDialog dialog = new ListDialog(this, ListDialog.SINGLE);
        String[] namesArray = names.toArray(new String[names.size()]);
        dialog.setItems(namesArray);
        dialog.setOnSingleSelectListener(listener);
//        SelectDialog dialog = new SelectDialog(this, R.style.transparentFrameWindowStyle,
//                listener, names);
        if (!this.isTerminating()) {
            dialog.show();
        }
        return dialog;
    }

    @Override
    public void onItemClick(Component view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                showDialog(new IDialog.ClickedListener() {
                    @Override
                    public void onClick(IDialog iDialog, int i) {
                        Operation operation = new Intent.OperationBuilder()
                                .withDeviceId("")
                                .withBundleName("com.lzy.imagepickerdemo")
                                .withAbilityName(ImageGridAbility.class.getName())
                                .build();


                        switch (i) {
                            case 0: // 直接调起相机
                                /**
                                 * 0.4.7 目前直接调起相机不支持裁剪，如果开启裁剪后不会返回图片，请注意，后续版本会解决
                                 *
                                 * 但是当前直接依赖的版本已经解决，考虑到版本改动很少，所以这次没有上传到远程仓库
                                 *
                                 * 如果实在有所需要，请直接下载源码引用。
                                 */
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                                Intent intent = new Intent();
                                intent.setOperation(operation);
                                intent.setParam(ImageGridAbility.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startAbilityForResult(intent, REQUEST_CODE_SELECT);
                                iDialog.hide();
                                break;
                            case 1:
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                                Intent intent1 = new Intent();
                                intent1.setOperation(operation);

                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);

                                startAbilityForResult(intent1, REQUEST_CODE_SELECT);
                                iDialog.hide();
                                break;
                            default:
                                break;
                        }
                    }

                }, names);


                break;
            default:
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName(ImagePreviewAbility.class.getPackage().getName())
                        .withAbilityName(ImagePreviewAbility.class.getName())
                        .build();
                //打开预览
                Intent intentPreview = new Intent();
                intentPreview.setOperation(operation);
                intentPreview.setParam(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.setParam(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.setParam(ImagePicker.EXTRA_FROM_ITEMS, true);
                startAbilityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    ArrayList<ImageItem> images = null;

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent data) {
        try {
            super.onAbilityResult(requestCode, resultCode, data);
            if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
                //添加图片返回
                if (data != null && requestCode == REQUEST_CODE_SELECT) {
                    images = (ArrayList<ImageItem>) data.getSerializableParam(ImagePicker.EXTRA_RESULT_ITEMS);
                    if (images != null) {
                        selImageList.addAll(images);
                        adapter.setImages(selImageList);
                    }
                }
            } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
                //预览图片返回
                if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                    images = (ArrayList<ImageItem>) data.getSerializableParam(ImagePicker.EXTRA_IMAGE_ITEMS);
                    if (images != null) {
                        selImageList.clear();
                        selImageList.addAll(images);
                        adapter.setImages(selImageList);
                    }
                }
            }
        }catch (Exception e){
            images = new ArrayList<>();
        }

    }


}
